<template>
	<view class="container">
		<uni-popup ref="specPopup" type="bottom" :safe-area="false" :mask-click="true">
			<view class="spec-modal">
				<!-- Header with close button -->
				<view class="modal-header">
					<view class="close-btn" @click="close">×</view>
				</view>

				<scroll-view scroll-y class="modal-content">
					<!-- Address Selection -->
					<view class="address-section" @click="selectAddress">
						<view class="address-icon">
							<text class="location-icon">📍</text>
						</view>
						<view class="address-info">
							<view v-if="selectedAddress" class="address-detail">
								{{selectedAddress.province}}{{selectedAddress.city}}{{selectedAddress.district}}{{ selectedAddress.detail }}
							</view>
							<view v-if="selectedAddress" class="contact-info">
								{{ selectedAddress.realName }} {{ selectedAddress.phone }}
							</view>
							<view v-else class="add-address-text">点击添加收货地址</view>
						</view>
						<view class="address-arrow">
							<text>›</text>
						</view>
					</view>

					<!-- Product info, color and size selection -->
					<view class="product-container">
						<view class="product-info">
							<image v-if="product.goodsCategory!=='TC'" :src="selectedSpec.picUrl | avatarUrlFind('1')"
								mode="aspectFill" class="product-image" @click="previewImage(selectedSpec.picUrl)">
							</image>
							<image v-if="product.goodsCategory==='TC'" :src="product.image | avatarUrlFind('1')"
								mode="aspectFill" class="product-image" @click="previewImage(product.image)"></image>
							<view class="info-right">
								<view class="price">
									<text class="current-price">
										<text style="font-size: 32rpx;">实付：</text>
										¥{{ currentPrice.salesPrice }}
									</text>
								</view>
								<view class="price">
									<text class="yuan">原价：</text>
									<text class="original-price">¥{{ currentPrice.dashingPrice }}</text>
								</view>
								<view class="selected-info">
									<view class="quantity-selector">
										<view class="quantity-btn" @click="decreaseQuantity">-</view>
										<input type="number" v-model="quantity" class="quantity-input" />
										<view class="quantity-btn" @click="increaseQuantity">+</view>
									</view>
								</view>
							</view>
						</view>

						<!-- Specification selection -->
						<view class="spec-section" v-if="product.goodsCategory==='P'||product.goodsCategory==='JP'">
							<view class="section-title">规格 ({{ product.speciList ? product.speciList.length : 0 }})
							</view>
							<view class="spec-options">
								<view v-for="(item, index) in product.speciList" :key="index" class="spec-option"
									:class="{ active: selectedSpec && selectedSpec.skuCode === item.skuCode }"
									@click="selectColor(item)">
									{{ item.speciName || '未知规格' }}
								</view>
							</view>
						</view>

						<view class="spec-section" v-if="product.goodsCategory==='TC'">
							<view class="section-title">包含商品 ({{ product.speciList ? product.speciList.length : 0 }})
							</view>
							<view class="spec-options">
								<view v-for="(item, index) in product.speciList" :key="index" class="spec-item">
									{{ item.speciName || '未知规格' }}x{{item.participationNum}}
								</view>
							</view>
						</view>
					</view>

					<!-- Payment method -->
					<view class="payment-section">
						<view class="payment-title">支付方式</view>
						<view class="payment-options">
							<view class="payment-option" @click="togglePayment('wechat')">
								<view class="payment-left">
									<text class="payment-name">微信支付</text>
								</view>
								<view class="payment-right">
									<view class="payment-checkbox"
										:class="{ checked: selectedPayments.includes('wechat') }">
									</view>
								</view>
							</view>
							<view class="payment-option" @click="togglePayment('balance')">
								<view class="payment-left">
									<text class="payment-name">储值余额</text>
									<text class="balance-amount">余额：¥{{ userBalance }}</text>
								</view>
								<view class="payment-right">
									<view class="payment-checkbox"
										:class="{ checked: selectedPayments.includes('balance') }">
									</view>
								</view>
							</view>
							<!-- 储值余额自定义输入 -->
							<view v-if="selectedPayments.includes('balance')" class="balance-input-section">
								<view class="balance-input-container">
									<text class="balance-input-label">使用余额：</text>
									<input type="digit" v-model="customBalanceAmount" class="balance-input"
										placeholder="请输入使用金额" @input="onBalanceInput" />
									<text class="balance-input-unit">元</text>
								</view>
								<view class="balance-tips">
									<text class="tips-text">可用余额：¥{{ userBalance }}，使用余额不能超过可用余额</text>
								</view>
							</view>
						</view>
					</view>

					<!-- Basic Information -->
					<view class="basic-info-section">
						<view class="info-item">
							<text class="item-label">商品金额</text>
							<text class="item-value">¥{{ totalPrice.dashingPrice }}</text>
						</view>
						<view class="info-item">
							<text class="item-label">折扣金额</text>
							<text
								class="item-value discount">-¥{{ (Number(totalPrice.dashingPrice) - Number(totalPrice.salesPrice)).toFixed(2) }}</text>
						</view>
						<!-- <view class="info-item">
              <text class="item-label">储值消耗</text>
              <text class="item-value">¥{{ totalPrice.salesPrice }}</text>
            </view> -->
					</view>

				</scroll-view>

				<!-- Fixed bottom area -->
				<view class="fixed-bottom">
					<view class="agreement-section">
						<view class="custom-checkbox" :class="{ checked: agreed }" @click="toggleAgreement">
							<text v-if="agreed" class="checkbox-inner">✓</text>
						</view>
						<text class="agreement-text">购买请阅读并签名同意<text class="link"
								@click="showAgreement">《服务协议》</text></text>
					</view>
					<!-- 支付方式组合信息 -->
					<!-- <view v-if="selectedPayments.length > 0" class="payment-summary">
						<view class="summary-item" v-if="selectedPayments.includes('balance') && paymentCombination.balanceAmount > 0">
							<text class="summary-label">储值支付：</text>
							<text class="summary-value">¥{{ paymentCombination.balanceAmount }}</text>
						</view>
						<view class="summary-item" v-if="selectedPayments.includes('wechat') && paymentCombination.wechatAmount > 0">
							<text class="summary-label">微信支付：</text>
							<text class="summary-value">¥{{ paymentCombination.wechatAmount }}</text>
						</view>
					</view> -->
					<view class="confirm-btn" @click="showSignatureDialog"
						:class="{ disabled: !paymentCombination.canPay }">
						{{ paymentCombination.canPay ? `立即支付 ¥${paymentCombination.totalAmount}` : '请选择支付方式' }}
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- Agreement Signature Dialog -->
		<uni-popup ref="agreementPopup" type="center">
			<view class="agreement-dialog">
				<view class="dialog-header">
					<text class="dialog-title">服务协议</text>
				</view>
				<view class="dialog-content">
					<text class="agreement-desc">购买请阅读签字同意瑞隆安的<text class="link"
							@click="showAgreement">《服务协议》</text></text>
					<view class="signature-area" @click="openSignature">
						<image v-if="signatureImage" :src="signatureImage" mode="aspectFit" class="signature-image">
						</image>
						<text v-else class="signature-label">点击签名</text>
					</view>
				</view>
				<view class="dialog-footer">
					<view class="dialog-btn cancel" @click="closeSignatureDialog">取消</view>
					<view class="dialog-btn confirm" @click="confirmAgreement">同意并继续</view>
				</view>
			</view>
		</uni-popup>

		<!-- Signature Popup -->
		<uni-popup ref="signaturePopup" type="center" :mask-click="false">
			<view class="signature-popup" @touchmove.stop.prevent>
				<view class="signature-header">
					<text>手写签名</text>
					<view class="signature-actions">
						<view class="action-btn" @click="clearSignature">重签</view>
						<view class="action-btn cancel" @click="closeSignature">取消</view>
						<view class="action-btn confirm" @click="confirmSignature">确定</view>
					</view>
				</view>
				<view class="signature-canvas-area" @touchmove.stop.prevent>
					<canvas canvas-id="signature" class="signature-canvas" @touchstart.stop.prevent="touchStart"
						@touchmove.stop.prevent="touchMove" @touchend.stop.prevent="touchEnd">
					</canvas>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import config from '@/config'
	import {
		getToken
	} from '@/utils/auth'
	import {
		createOrder,
		lqlPay
	} from '@/api/order.js'
	import {
		listAddress
	} from '@/api/userAddress.js'
	import {
		getInfo
	} from '@/api/vipUser.js'

	export default {
		name: 'SpecificationModal',
		props: {
			product: {
				type: Object,
				required: true,
				default: () => ({})
			},
			salesPrice: {
				type: [String, Number],
				required: false,
				default: '0'
			},
			dashingPrice: {
				type: [String, Number],
				required: false,
				default: '0'
			}
		},
		data() {
			return {
				selectedSpec: {},
				quantity: 1,
				paymentMethod: 'wechat',
				agreed: false,
				showSignature: false,
				signatureImage: '',
				context: null,
				isDrawing: false,
				lastX: 0,
				lastY: 0,
				drawTimer: null,
				points: [], // 添加签名点数组
				hasSigned: false, // 添加是否已签名标志
				selectedPayments: ['wechat'], // 新增：存储选中的支付方式
				customBalanceAmount: '', // 新增：储值余额自定义输入金额
				userBalance: 0.00, // 新增：用户可用余额
				selectedAddress: null, // 新增：选中的地址信息
				addressList: [] // 新增：地址列表
			}
		},
		watch: {
			product: {
				immediate: true,
				handler(newVal) {
					// 当商品数据更新时，根据商品类型处理
					if (newVal && newVal.speciList && newVal.speciList.length > 0) {
						if (newVal.goodsCategory === 'TC') {
							// 套餐商品不需要选择规格，清空selectedSpec
							this.selectedSpec = {}
							console.log('套餐商品，无需选择规格')
						} else {
							// 普通商品默认选中第一个规格
							this.selectColor(newVal.speciList[0])
							this.selectedSpec = newVal.speciList[0]
							console.log(this.selectedSpec)
						}
					} else {
						this.selectedSpec = {}
					}
				}
			}
		},
		mounted() {
			// 初始化时默认选择微信支付
			this.selectedPayments = ['wechat'];
			this.loadAddressList(); // 加载地址列表
			this.getInfo()

			// 监听地址选择事件
			uni.$on('addressSelected', this.handleAddressSelected);
		},
		beforeDestroy() {
			// 移除事件监听
			uni.$off('addressSelected', this.handleAddressSelected);
		},
		computed: {
			// 当前选中规格的价格
			currentPrice() {
				// 如果是套餐商品，使用套餐价格
				if (this.product.goodsCategory === 'TC') {
					return {
						salesPrice: this.product.packagePrice || '0',
						dashingPrice: this.product.dashingPrice || '0'
					}
				}

				// 普通商品使用选中的规格价格
				if (this.selectedSpec && this.selectedSpec.salesPrice) {
					return {
						salesPrice: this.selectedSpec.salesPrice,
						dashingPrice: this.selectedSpec.dashingPrice
					}
				}

				// 默认使用传入的价格
				return {
					salesPrice: this.salesPrice,
					dashingPrice: this.dashingPrice
				}
			},
			// 计算总价
			totalPrice() {
				return {
					salesPrice: (Number(this.currentPrice.salesPrice) * this.quantity).toFixed(2),
					dashingPrice: (Number(this.currentPrice.dashingPrice) * this.quantity).toFixed(2)
				}
			},
			// 计算支付方式组合
			paymentCombination() {
				const totalAmount = Number(this.totalPrice.salesPrice);
				let balanceAmount = 0;
				let wechatAmount = 0;

				// 如果选择了储值余额且有输入金额
				if (this.selectedPayments.includes('balance') && this.customBalanceAmount) {
					balanceAmount = Math.min(Number(this.customBalanceAmount), Number(this.userBalance));
				}

				// 如果选择了微信支付，计算需要支付的金额
				if (this.selectedPayments.includes('wechat')) {
					wechatAmount = Math.max(0, totalAmount - balanceAmount);
				}

				// 如果只选择了储值余额，确保不超过总金额
				if (this.selectedPayments.includes('balance') && !this.selectedPayments.includes('wechat')) {
					balanceAmount = Math.min(balanceAmount, totalAmount);
					wechatAmount = 0;
				}

				return {
					totalAmount: totalAmount.toFixed(2),
					balanceAmount: balanceAmount.toFixed(2),
					wechatAmount: wechatAmount.toFixed(2),
					canPay: this.selectedPayments.length > 0 && (balanceAmount + wechatAmount >= totalAmount)
				};
			}
		},
		methods: {
			open() {
				this.$refs.specPopup.open()
			},
			close() {
				this.$refs.specPopup.close()
			},
			selectAddress() {
				// 跳转到地址选择页面
				uni.navigateTo({
					url: '/subPackage_1/pages/mine/address/address-list?selectMode=true'
				})
			},
			// 选择规格
			selectColor(spec) {
				console.log('选择规格:', spec)
				if (this.product.goodsCategory === 'TC') {
					// 套餐商品不需要选择规格，价格固定
					console.log('套餐商品，价格固定')
				} else {
					this.selectedSpec = spec
					// 触发事件通知父组件价格变化
					this.$emit('spec-change', {
						salesPrice: spec.salesPrice,
						dashingPrice: spec.dashingPrice,
						spec: spec
					})
				}

				// 如果已选择储值余额，更新默认金额为新的商品总价
				if (this.selectedPayments.includes('balance')) {
					this.customBalanceAmount = this.totalPrice.salesPrice;
				}
			},
			selectSize(size) {
				this.selectedSize = size
			},
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--
					// 如果已选择储值余额，更新默认金额为新的商品总价
					if (this.selectedPayments.includes('balance')) {
						this.customBalanceAmount = this.totalPrice.salesPrice;
					}
				}
			},
			increaseQuantity() {
				this.quantity++
				// 如果已选择储值余额，更新默认金额为新的商品总价
				if (this.selectedPayments.includes('balance')) {
					this.customBalanceAmount = this.totalPrice.salesPrice;
				}
			},
			togglePayment(method) {
				// 当余额为0时，禁止选择储值余额并确保取消选中
				if (method === 'balance' && Number(this.userBalance) <= 0) {
					uni.showToast({
						title: '暂无可用余额',
						icon: 'none'
					})
					this.selectedPayments = this.selectedPayments.filter(m => m !== 'balance')
					this.customBalanceAmount = ''
					return
				}
				if (this.selectedPayments.includes(method)) {
					// 如果已选中，则取消选择
					this.selectedPayments = this.selectedPayments.filter(m => m !== method);
				} else {
					// 如果未选中，则添加到选中列表（支持多选）
					this.selectedPayments.push(method);
				}

				// 如果取消选择储值余额，清空自定义输入金额
				if (method === 'balance' && !this.selectedPayments.includes('balance')) {
					this.customBalanceAmount = '';
				}

				// 如果选择储值余额且没有输入金额，默认填入当前商品总价
				if (method === 'balance' && this.selectedPayments.includes('balance') && !this.customBalanceAmount) {
					this.customBalanceAmount = this.totalPrice.salesPrice;
				}

				// 检查并更新支付方式
				this.checkAndUpdatePaymentMethods();
			},
			onBalanceInput(e) {
				const value = e.detail.value;
				if (value === '') {
					this.customBalanceAmount = '';
					// 无输入时，取消选择储值余额
					this.selectedPayments = this.selectedPayments.filter(method => method !== 'balance')
				} else {
					// 只允许数字和小数点，且最多两位小数
					let newValue = value.replace(/[^\d.]/g, '');

					// 处理多个小数点的情况
					const dotIndex = newValue.indexOf('.');
					if (dotIndex !== -1) {
						const beforeDot = newValue.substring(0, dotIndex);
						const afterDot = newValue.substring(dotIndex + 1);
						if (afterDot.length > 2) {
							afterDot = afterDot.substring(0, 2);
						}
						newValue = beforeDot + '.' + afterDot;
					}

					// 检查是否超过可用余额
					if (Number(newValue) > Number(this.userBalance)) {
						uni.showToast({
							title: '使用余额不能超过可用余额',
							icon: 'none'
						});
						this.customBalanceAmount = this.userBalance.toString();
					} else if (Number(newValue) > Number(this.totalPrice.salesPrice)) {
						// 检查是否超过商品总价
						uni.showToast({
							title: '使用余额不能超过商品总价',
							icon: 'none'
						});
						this.customBalanceAmount = this.totalPrice.salesPrice;
					} else {
						this.customBalanceAmount = newValue;
						// 若输入为0或空，自动取消储值余额选中
						if (!newValue || Number(newValue) <= 0) {
							this.selectedPayments = this.selectedPayments.filter(method => method !== 'balance')
						}
					}
				}

				// 检查储值余额是否等于商品支付价格，如果是则取消微信支付选择
				this.checkAndUpdatePaymentMethods();
			},
			checkAndUpdatePaymentMethods() {
				// 检查储值余额与应付金额关系
				const hasBalanceInput = this.customBalanceAmount !== '' && this.customBalanceAmount !== null
				const balanceVal = Number(this.customBalanceAmount)
				const totalVal = Number(this.totalPrice.salesPrice)

				if (hasBalanceInput && balanceVal >= totalVal) {
					// 储值余额足够或超出，自动取消微信支付
					this.selectedPayments = this.selectedPayments.filter(method => method !== 'wechat')
					if (!this.selectedPayments.includes('balance')) {
						this.selectedPayments.push('balance')
					}
				} else if (hasBalanceInput && balanceVal > 0 && balanceVal < totalVal) {
					// 输入了部分余额且小于应付金额，自动选择微信支付
					if (!this.selectedPayments.includes('wechat')) {
						this.selectedPayments.push('wechat')
					}
					// 确保已勾选余额
					if (!this.selectedPayments.includes('balance')) {
						this.selectedPayments.push('balance')
					}
				}
			},
			toggleAgreement() {
				this.agreed = !this.agreed
			},
			confirmSelection() {
				if (!this.agreed) {
					uni.showToast({
						title: '请先同意服务协议',
						icon: 'none'
					})
					return
				}
				// Implement purchase logic here
				uni.showToast({
					title: '购买成功',
					icon: 'success'
				})
				this.close()
			},

			showSignatureDialog() {
				// 校验必须有地址
				if (!this.selectedAddress) {
					uni.showToast({
						title: '请先选择收货地址',
						icon: 'none'
					})
					return
				}
				
				// 当按钮处于禁用状态时，直接返回，不弹出签名
				if (!this.paymentCombination || !this.paymentCombination.canPay) {
					return
				}
				if (!this.agreed) {
					uni.showToast({
						title: '请先同意服务协议',
						icon: 'none'
					})
					return
				}
				this.$refs.agreementPopup.open()
			},

			closeSignatureDialog() {
				// 如果没有签名，不允许关闭
				// if (!this.signatureImage) {
				// 	uni.showToast({
				// 		title: '请先完成签名',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				this.$refs.agreementPopup.close()
			},

			confirmAgreement() {
				if (!this.signatureImage) {
					uni.showToast({
						title: '请先完成签名',
						icon: 'none'
					})
					return
				}

				

				this.$refs.agreementPopup.close()

				//拼装订单数据
				let mallOrder = {}
				mallOrder.userId = this.$store.state.user.userId
				mallOrder.orderType = '1'
				mallOrder.totalNum = this.quantity
				mallOrder.totalAmount = this.totalPrice.dashingPrice
				mallOrder.discountAmount = (Number(this.totalPrice.dashingPrice) - Number(this.totalPrice.salesPrice))
					.toFixed(2)
				mallOrder.payableAmount = this.totalPrice.salesPrice
				mallOrder.goodsCategory = this.product.goodsCategory
				mallOrder.drugCode = this.product.drugCode
				mallOrder.drugId = this.product.id

				//TODO 地址相关信息
				let orderAddress = {}
				orderAddress.receiveUserName = this.selectedAddress ? this.selectedAddress.realName : ''
				orderAddress.receiveUserPhone = this.selectedAddress ? this.selectedAddress.phone : ''
				orderAddress.receiveUserAddress = this.selectedAddress ? this.selectedAddress.detail : ''
				orderAddress.receiveProvince = this.selectedAddress ? this.selectedAddress.province : ''
				orderAddress.receiveCity = this.selectedAddress ? this.selectedAddress.city : ''
				orderAddress.receiveCounty = this.selectedAddress ? this.selectedAddress.district : ''
				mallOrder.orderAddress = orderAddress

				mallOrder.onlinePayMode = this.selectedPayments.join(',') // 使用选中的支付方式
				mallOrder.picUrl = this.signatureImage

				let orderDetailList = []
				if (this.product.goodsCategory !== 'TC') {
					this.selectedSpec.price = this.currentPrice.salesPrice
					this.selectedSpec.num = this.quantity
					this.selectedSpec.amount = this.totalPrice.salesPrice
					orderDetailList.push(this.selectedSpec)
					mallOrder.orderDetailList = orderDetailList
				}

				// 支持多种支付方式
				let orderPayList = []

				// 储值余额支付
				if (this.selectedPayments.includes('balance') && this.paymentCombination.balanceAmount > 0) {
					let balancePayDetail = {}
					balancePayDetail.payMode = 'balance' // 储值余额支付
					balancePayDetail.paymentAmount = this.paymentCombination.balanceAmount
					orderPayList.push(balancePayDetail)
				}

				// 微信支付
				if (this.selectedPayments.includes('wechat') && this.paymentCombination.wechatAmount > 0) {
					let wechatPayDetail = {}
					wechatPayDetail.payMode = 'wechat' // 微信支付
					wechatPayDetail.paymentAmount = this.paymentCombination.wechatAmount
					orderPayList.push(wechatPayDetail)
				}

				mallOrder.orderPayList = orderPayList


				console.log(mallOrder)

				uni.showLoading({
					title: '正在提交订单...'
				})

				createOrder(mallOrder).then(res => {
					if (res.code === 200 && res.data) {

						uni.hideLoading();

						// 如果只使用储值余额支付，直接跳转到订单页面
						if (this.selectedPayments.includes('balance') && !this.selectedPayments.includes(
								'wechat')) {
							uni.showToast({
								title: '支付成功',
								icon: 'success'
							});
							setTimeout(() => {
								uni.reLaunch({
									url: '/subPackage_1/pages/order/order-list?tab_cur=0'
								});
							}, 1500);
							return;
						}

						// 如果包含微信支付，需要调起微信支付
						if (this.selectedPayments.includes('wechat')) {
							uni.showLoading({
								title: '拼命加载中...'
							});
							// 请求三方支付，获取小程序拉取支付内容
							lqlPay({
								orderId: res.data
							}).then(res1 => {
								console.log(res1)
								const param = res1.data.result
								console.log(param)
								const payInfo = JSON.parse((param.payInfo))

								// 根据返回信息,调起微信支付页面
								uni.requestPayment({
									timeStamp: payInfo.timeStamp,
									nonceStr: payInfo.nonceStr,
									package: payInfo.package,
									signType: payInfo.signType,
									paySign: payInfo.paySign,
									// 输入密码,出现新页面点击完成后的事件, 去查单是否成功
									success: function(res2) {
										console.log("已经支付", res2);
										uni.reLaunch({
											url: '/subPackage_1/pages/order/order-list?tab_cur=0'
										});
									},
									fail: function(err) {
										uni.hideLoading();
										console.log("调起支付失败", err);
									},
									complete: function(res3) {
										console.log("取消支付", res3);
										uni.hideLoading();
										uni.reLaunch({
											url: '/subPackage_1/pages/order/order-list?tab_cur=0'
										});
									}
								})

							}).catch(res4 => {
								console.error("微信统一下单失败", res4);
							})
						}

					}
				}).catch(error => {
					uni.hideLoading()
					uni.showToast({
						title: error.message || '创建订单失败',
						icon: 'none'
					})
				})
			},

			showAgreement() {
				// 跳转到购买协议页面
				uni.navigateTo({
					url: '/pages/agreement/purchase-agreement'
				})
			},

			openSignature() {
				this.$refs.signaturePopup.open()
				// 初始化画布
				this.$nextTick(() => {
					const ctx = uni.createCanvasContext('signature', this)
					ctx.strokeStyle = '#000000'
					ctx.lineWidth = 2 // 减小线宽，提高流畅度
					ctx.lineCap = 'round'
					ctx.lineJoin = 'round'
					this.context = ctx

					// 设置画布背景色
					const query = uni.createSelectorQuery().in(this)
					query.select('.signature-canvas')
						.boundingClientRect(data => {
							this.context.fillStyle = '#f8f8f8'
							this.context.fillRect(0, 0, data.width, data.height)
							this.context.draw(true)
						}).exec()
				})
			},

			closeSignature() {
				this.$refs.signaturePopup.close()
				this.points = []
			},

			clearSignature() {
				if (this.drawTimer) {
					clearTimeout(this.drawTimer)
					this.drawTimer = null
				}

				this.hasSigned = false // 清除签名时重置标志

				const query = uni.createSelectorQuery().in(this)
				query.select('.signature-canvas')
					.boundingClientRect(data => {
						this.context.clearRect(0, 0, data.width, data.height)
						this.context.fillStyle = '#f8f8f8'
						this.context.fillRect(0, 0, data.width, data.height)
						this.context.draw()
					}).exec()
			},

			touchStart(e) {
				const touch = e.changedTouches[0]
				this.isDrawing = true
				this.lastX = touch.x
				this.lastY = touch.y
				this.hasSigned = true // 开始绘制时标记已签名

				// 开始绘制点
				this.context.beginPath()
				this.context.arc(touch.x, touch.y, 1, 0, 2 * Math.PI)
				this.context.fill()
				this.context.draw(true)
			},

			touchMove(e) {
				if (!this.isDrawing) return
				const touch = e.changedTouches[0]
				const currentX = touch.x
				const currentY = touch.y

				// 清除之前的定时器
				if (this.drawTimer) {
					clearTimeout(this.drawTimer)
				}

				// 使用定时器延迟绘制，避免过于频繁
				this.drawTimer = setTimeout(() => {
					this.context.beginPath()
					this.context.moveTo(this.lastX, this.lastY)
					this.context.lineTo(currentX, currentY)
					this.context.stroke()
					this.context.draw(true)

					this.lastX = currentX
					this.lastY = currentY
				}, 8) // 8ms的延迟，约120fps
			},

			touchEnd(e) {
				if (!this.isDrawing) return

				const touch = e.changedTouches[0]
				// 确保最后一个点被绘制
				this.context.beginPath()
				this.context.moveTo(this.lastX, this.lastY)
				this.context.lineTo(touch.x, touch.y)
				this.context.stroke()
				this.context.draw(true)

				this.isDrawing = false
				if (this.drawTimer) {
					clearTimeout(this.drawTimer)
					this.drawTimer = null
				}
			},

			async confirmSignature() {
				if (!this.hasSigned) {
					uni.showToast({
						title: '请先签名',
						icon: 'none'
					})
					return
				}

				try {
					uni.showLoading({
						title: '保存中...',
						mask: true
					})

					// 1. 将画布转换为临时文件
					const tempFile = await new Promise((resolve, reject) => {
						uni.canvasToTempFilePath({
							canvasId: 'signature',
							success: res => resolve(res.tempFilePath),
							fail: err => reject(new Error('生成签名图片失败'))
						}, this)
					})

					// 2. 上传签名图片
					const uploadResult = await new Promise((resolve, reject) => {
						uni.uploadFile({
							url: config.baseUrl + '/common/upload',
							filePath: tempFile,
							name: 'file',
							header: {
								'Authorization': 'Bearer ' + getToken(),
								'requestType': 'app'
							},
							formData: {
								type: 'signature',
								orderId: this.product.id || '',
								timestamp: Date.now()
							},
							success: (uploadRes) => {
								console.log('上传响应原始数据:', uploadRes)
								try {
									const result = JSON.parse(uploadRes.data)
									console.log('解析后的响应数据:', result)
									if (result.code === 200) {
										if (result && result.url) {
											this.signatureImage = result.url
											resolve(result)
										} else if (typeof result === 'string') {
											resolve({
												url: result
											})
										} else {
											reject(new Error('返回数据格式错误'))
										}
									} else {
										reject(new Error(result.msg || '上传失败'))
									}
								} catch (e) {
									console.error('解析响应数据失败:', e)
									reject(new Error('解析响应失败'))
								}
							},
							fail: (error) => {
								console.error('上传请求失败:', error)
								reject(new Error('上传失败，请重试'))
							}
						})
					})

					// 3. 更新签名图片
					// this.signatureImage = uploadResult.url
					this.$refs.signaturePopup.close()

					// uni.showToast({
					// 	title: '签名已保存',
					// 	icon: 'success'
					// })

				} catch (error) {
					uni.showToast({
						title: error.message || '保存失败，请重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},
			async loadAddressList() {
				try {
					if (getToken()) {
						listAddress({
							userId: this.$store.state.user.userId
						}).then(res => {
							if (res.code === 200) {
								this.addressList = res.rows;
								// 优先选择标记为默认的地址，如果没有则选择第一个地址
								if (this.addressList.length > 0) {
									// 查找默认地址
									const defaultAddr = this.addressList.find(item => item.isDefault === '1');
									if (defaultAddr) {
										this.selectedAddress = defaultAddr;
										console.log('使用默认地址:', this.selectedAddress);
									} else {
										// 如果没有默认地址，使用第一个地址
										this.selectedAddress = this.addressList[0];
										console.log('使用第一个地址作为默认地址:', this.selectedAddress);
									}
								}
							} else {
								uni.showToast({
									title: res.msg || '获取地址列表失败',
									icon: 'none'
								});
							}
						})
					}

				} catch (error) {
					uni.showToast({
						title: error.message || '获取地址列表失败',
						icon: 'none'
					});
				}
			},
			// 处理地址选择
			handleAddressSelected(address) {
				this.selectedAddress = address;
				uni.showToast({
					title: '地址选择成功',
					icon: 'success'
				});
			},

			getInfo() {
				if (getToken()) {
					getInfo(this.$store.state.user.userId).then(res => {
						this.userBalance = res.data.usableBalance
						// 若余额为0，确保取消选择储值余额并清空输入
						if (Number(this.userBalance) <= 0) {
							this.selectedPayments = this.selectedPayments.filter(method => method !== 'balance')
							this.customBalanceAmount = ''
						}
					})
				}

			},

			previewImage(picUrl) {
				picUrl = config.remotePicUrlPd + picUrl
				console.log('点击预览图片，当前规格:', picUrl)

				// 只预览当前选中规格的图片
				if (picUrl) {
					uni.previewImage({
						current: picUrl, // 当前显示图片的链接
						urls: [picUrl], // 只包含当前规格的图片
						success: () => {
							console.log('图片预览成功')
						},
						fail: (err) => {
							console.error('图片预览失败:', err)
							uni.showToast({
								title: '图片预览失败',
								icon: 'none'
							})
						}
					})
				} else {
					uni.showToast({
						title: '暂无图片可预览',
						icon: 'none'
					})
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.spec-modal {
		background-color: #f6f6f6;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		position: relative;
		height: 92vh;
		display: flex;
		flex-direction: column;
		overflow: hidden; // 防止内容溢出
	}

	.modal-header {
		background-color: #f6f6f6;
		text-align: right;
		// padding: 10rpx 10rpx;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		flex-shrink: 0;
		padding-right: 10rpx;
	}

	.close-btn {
		font-size: 60rpx;
		color: #999;
		padding: 10rpx;
	}

	.modal-content {
		flex: 1;
		background-color: #f6f6f6;
		padding: 0 20rpx;
		height: 0;
		position: relative;
		overflow-y: auto;
		margin-bottom: 120px;
	}

	// 移除之前的底部间距占位
	scroll-view {
		height: 100%;
	}

	.address-section {
		display: flex;
		align-items: center;
		padding: 20rpx 26rpx;
		margin-bottom: 30rpx;
		background: #fff;
		border-radius: 10px;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

		.address-icon {
			font-size: 40rpx;
			margin-right: 20rpx;
		}

		.address-info {
			flex: 1;

			.address-detail {
				font-size: 28rpx;
				color: #333;
				margin-bottom: 10rpx;
			}

			.contact-info {
				font-size: 24rpx;
				color: #666;
			}

			.add-address-text {
				font-size: 28rpx;
				color: #666;
				text-align: center;
				padding: 20rpx 0;
			}
		}

		.address-arrow {
			color: #999;
			font-size: 32rpx;
		}
	}

	.product-info {
		display: flex;
		margin-bottom: 30rpx;
		padding: 20rpx;
		position: relative;

		.product-image {
			width: 240rpx;
			height: 240rpx;
			border-radius: 18rpx;
			box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1),
				0 16rpx 28rpx rgba(0, 0, 0, 0.08),
				0 2rpx 4rpx rgba(255, 255, 255, 0.1) inset;
			position: relative;
			top: -70rpx;
			margin-bottom: -60rpx;
			// border: 1rpx solid rgba(255, 255, 255, 0.2);
			transform: perspective(800rpx) rotateX(2deg);
		}

		.info-right {
			flex: 1;
			margin-left: 46rpx;

			.price {
				margin-bottom: 10rpx;

				.current-price {
					color: #000;
					font-size: 48rpx;
					margin-right: 10rpx;
				}

				.original-price {
					color: #999;
					text-decoration: line-through;
					font-size: 32rpx;
				}

				.yuan {
					color: #999;
					font-size: 32rpx;
				}
			}

			.selected-info {
				display: flex;
				align-items: center;
				color: #666;
				font-size: 28rpx;
				margin-top: 20rpx;

				.quantity-selector {
					display: flex;
					align-items: center;

					.quantity-btn {
						width: 50rpx;
						height: 50rpx;
						border: 2rpx solid #ddd;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 32rpx;
						color: #333;
						background: #fff;
					}

					.quantity-input {
						width: 80rpx;
						height: 50rpx;
						text-align: center;
						border-top: 2rpx solid #ddd;
						border-bottom: 2rpx solid #ddd;
						margin: 0;
						font-size: 28rpx;
					}
				}
			}
		}
	}

	.product-container {
		background: #fff;
		border-radius: 10px;
		padding: 20rpx 10rpx;
		margin-bottom: 30rpx;
		margin-top: 60rpx;
	}

	.spec-section {
		margin-bottom: 30rpx;
		padding: 0 20rpx;

		.section-title {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 20rpx;
		}

		.spec-options {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			.spec-option {
				min-width: 120rpx;
				text-align: center;
				padding: 15rpx 30rpx;
				border: 2rpx solid #ddd;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #333;

				&.active {
					border-color: #09ab4f;
					color: #09ab4f;
				}
			}

			.spec-item {
				min-width: 120rpx;
				text-align: center;
				padding: 15rpx 30rpx;
				background: #f8f8f8;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #666;
				border: none;
			}
		}
	}

	.quantity-section {
		margin-bottom: 30rpx;

		.quantity-selector {
			display: flex;
			align-items: center;

			.quantity-btn {
				width: 60rpx;
				height: 60rpx;
				border: 2rpx solid #ddd;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
			}

			.quantity-input {
				width: 80rpx;
				height: 60rpx;
				text-align: center;
				border-top: 2rpx solid #ddd;
				border-bottom: 2rpx solid #ddd;
			}
		}
	}

	.payment-section {
		margin-bottom: 30rpx;
		background: #fff;
		border-radius: 10px;
		padding: 20rpx 20rpx;

		.payment-title {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 20rpx;
		}

		.payment-options {
			.payment-option {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 20rpx;
				padding: 15rpx 10rpx;

				.payment-left {
					flex: 1;
					display: flex;
					align-items: center;

					.payment-name {
						font-size: 30rpx;
						color: #000;
					}

					.balance-amount {
						font-size: 24rpx;
						color: #999;
						margin-left: 20rpx;
					}
				}

				.payment-right {
					.payment-checkbox {
						width: 40rpx;
						height: 40rpx;
						border: 2rpx solid #ddd;
						border-radius: 50%;
						position: relative;

						&.checked {
							border-color: #09ab4f;
							background-color: #09ab4f;

							&::after {
								content: '';
								position: absolute;
								width: 20rpx;
								height: 20rpx;
								background-color: #fff;
								border-radius: 50%;
								top: 50%;
								left: 50%;
								transform: translate(-50%, -50%);
							}
						}
					}
				}
			}

			.balance-input-section {
				margin-top: 20rpx;
				padding: 20rpx;
				background: #f8f8f8;
				border-radius: 10rpx;

				.balance-input-container {
					display: flex;
					align-items: center;
					margin-bottom: 15rpx;

					.balance-input-label {
						font-size: 28rpx;
						color: #333;
						margin-right: 15rpx;
					}

					.balance-input {
						flex: 1;
						height: 60rpx;
						border: 2rpx solid #ddd;
						border-radius: 8rpx;
						padding: 0 15rpx;
						font-size: 28rpx;
						background: #fff;
					}

					.balance-input-unit {
						font-size: 28rpx;
						color: #666;
						margin-left: 10rpx;
					}
				}

				.balance-tips {
					.tips-text {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
		}
	}

	.basic-info-section {
		margin-bottom: 180rpx; // 增加底部间距，为固定底部区域留出空间
		background: #fff;
		border-radius: 10px;
		padding: 20rpx 20rpx;

		.info-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 15rpx 0;
			// border-bottom: 1rpx solid #eee;

			&:last-child {
				border-bottom: none;
			}

			.item-label {
				font-size: 28rpx;
				color: #666;
			}

			.item-value {
				font-size: 28rpx;
				color: #000;
				font-weight: bold;

				&.discount {
					color: #f00;
					font-weight: bold;
				}
			}
		}
	}

	.agreement-section {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-top: 1rpx solid #f5f5f5;

		.custom-checkbox {
			width: 32rpx;
			height: 32rpx;
			border-radius: 50%;
			border: 2rpx solid #ddd;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.2s;

			&.checked {
				background-color: #09ab4f;
				border-color: #09ab4f;
			}

			.checkbox-inner {
				color: #fff;
				font-size: 20rpx;
				line-height: 1;
				transform: translateY(-1rpx);
			}
		}

		.agreement-text {
			font-size: 20rpx;
			color: #666;
			margin-left: 10rpx;

			.link {
				color: #09ab4f;
			}
		}
	}

	.confirm-btn {
		background-color: #09ab4f;
		color: #fff;
		text-align: center;
		font-size: 32rpx;
		padding: 30rpx;

		&.disabled {
			background-color: #ccc;
			color: #999;
		}
	}

	.fixed-bottom {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 1;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
	}

	.payment-summary {
		padding: 20rpx 30rpx;
		background: #f8f8f8;
		border-radius: 10px;
		margin-bottom: 20rpx;

		.summary-item {
			display: flex;
			align-items: center;
			margin-bottom: 10rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.summary-label {
				font-size: 28rpx;
				color: #666;
				margin-right: 10rpx;
			}

			.summary-value {
				font-size: 28rpx;
				color: #000;
				font-weight: bold;
			}
		}
	}

	.agreement-dialog {
		width: 600rpx;
		background: #fff;
		border-radius: 20rpx;
		overflow: hidden;

		.dialog-header {
			padding: 30rpx;
			text-align: center;
			border-bottom: 1rpx solid #eee;

			.dialog-title {
				font-size: 32rpx;
				color: #000;
				font-weight: 500;
			}
		}

		.dialog-content {
			padding: 40rpx 30rpx;

			.agreement-desc {
				font-size: 28rpx;
				color: #B8B8B8;
				text-align: center;
				margin-bottom: 30rpx;

				.link {
					color: #09ab4f;
				}
			}

			.signature-area {
				margin-top: 16px;
				height: 200rpx;
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border: 2rpx dashed #ddd;

				.signature-image {
					width: 100%;
					height: 100%;
					object-fit: contain;
				}

				.signature-label {
					font-size: 28rpx;
					color: #999;
				}
			}
		}

		.dialog-footer {
			display: flex;
			border-top: 1rpx solid #eee;

			.dialog-btn {
				flex: 1;
				text-align: center;
				padding: 25rpx 0;
				font-size: 30rpx;

				&.cancel {
					color: #666;
					border-right: 1rpx solid #eee;
				}

				&.confirm {
					color: #09ab4f;
				}
			}
		}
	}

	.signature-popup {
		width: 100vw;
		height: 100vh;
		background: #fff;
		display: flex;
		flex-direction: column;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 999;
		overflow: hidden;
		touch-action: none;
		overscroll-behavior: contain;

		.signature-header {
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1rpx solid #eee;
			background: #fff;
			position: relative;
			z-index: 1;

			text {
				font-size: 32rpx;
				color: #000;
				font-weight: 500;
			}

			.signature-actions {
				display: flex;
				gap: 20rpx;

				.action-btn {
					font-size: 32rpx;
					padding: 10rpx 30rpx;
					border-radius: 4rpx;

					&.cancel {
						color: #999;
					}

					&.confirm {
						color: #fff;
						background: #09ab4f;
					}
				}
			}
		}

		.signature-canvas-area {
			flex: 1;
			position: relative;
			background: #fff;
			width: 100%;
			height: 100%;
			padding: 20rpx;
			box-sizing: border-box;
			overflow: hidden;
			touch-action: none;
			overscroll-behavior: contain;

			.signature-canvas {
				width: 100% !important;
				height: 100% !important;
				background: #f8f8f8;
				border-radius: 12rpx;
				touch-action: none;
				overscroll-behavior: contain;
			}
		}
	}
</style>